<template>
  <div>
    <!-- 地图选择按钮 -->
    <el-input
      v-model="address"
      size="small"
      clearable
      placeholder="请选择地图"
      @focus="focusMap"
    ></el-input>
    <!-- 地图弹窗 -->
    <ComDialog
      ref="mapDialog"
      :option="option"
      :visible.sync="visible"
      @on-submit="mapSure"
    >
      <div>
        <div class="sear-map">
          <el-select
            style="width: 100%"
            v-model="address"
            filterable
            remote
            reserve-keyword
            clearable
            placeholder="搜地点"
            :remote-method="remoteMethod"
            :loading="loading"
            @change="tipChange"
          >
            <el-option
              v-for="item in tips"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.district
              }}</span>
            </el-option>
          </el-select>
        </div>
        <div ref="asd" style="width: 100%; height: 450px"></div>
      </div>
    </ComDialog>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import ComDialog from "./com-dialog.vue";

// 高德地图 key
const mapKey = "6dabd75cbdff12029510b4f886c90c46";

export default {
  name: "comInputMap",
  components: { ComDialog },
  props: {
    value: {
      type: Array,
      default: () => [],
    },

    params: {
      type: Object,
      default: () => {
        return {
          zoom: 10, //地图显示的缩放级别
          zoomEnable: true, // 是否缩放
          dragEnable: true, // 是否左右移动
          resizeEnable: true,
          keyboardEnable: false,
        };
      },
    },
  },
  data() {
    return {
      visible: false,
      address: "", //详细地址
      lonLat: [116.4012765, 39.9235306], //经纬度
      loading: false,
      tips: [],
      projectMapMarker: undefined,
      map: undefined,
      option: {
        title: "请选择地图", // 标题
        width: "75%",
        btnAlign: "right",
        cancelBtn: false,
      },
    };
  },
  created() {
    if (this.value.length == 3) {
      this.lonLat = [this.value[0], this.value[1]];
      this.address = this.value[2];
    }
  },
  methods: {
    mapSure(done, loading) {
      if (this.address === "" || this.lonLat.length === 0) {
        this.$message({
          message: "没有选择地址",
          type: "warning",
        });
        loading();
      } else {
        const data = [...this.lonLat, ...[this.address]];
        this.$emit("update:value", data);
        done();
      }
    },
    focusMap() {
      this.visible = true;
      let that = this;
      AMapLoader.load({
        key: mapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Geocoder",
          "AMap.AutoComplete ", //2.0版本是AMap.AutoComplete，    2.0以下是AMap.Autocomplete
        ],
      }).then((AMap) => {
        that.initMap();
      });
    },
    //地图初始化
    initMap() {
      console.log(this.value);
      var chartDom = this.$refs["asd"];
      this.map = new AMap.Map(chartDom, {
        center: this.lonLat,
        ...this.params,
      });
      this.map.on("click", this.mapClick);
    },

    //远程搜所
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        const that = this;
        AMap.plugin("AMap.AutoComplete", function () {
          // 实例化Autocomplete
          const autoOptions = {
            city: "北京",
          };
          const autoComplete = new AMap.AutoComplete(autoOptions);
          autoComplete.search(query, function (status, result) {
            let res = result.tips || []; // 搜索成功时，result即是对应的匹配数据
            that.tips = res.filter((item) => {
              return item.id !== "";
            });
            that.loading = false;
          });
        });
      } else {
        this.tips = [];
      }
    },
    tipChange(value) {
      //下拉选择
      for (const tip of this.tips) {
        if (value === tip.id) {
          if (this.projectMapMarker !== undefined) {
            // 如果点标记已存在则先移除原点
            this.map.remove(this.projectMapMarker);
            this.lonLat = [];
          }
          this.projectMapMarker = new AMap.Marker({
            position: new AMap.LngLat(tip.location.lng, tip.location.lat),
          });
          this.lonLat = [tip.location.lng, tip.location.lat];
          this.map.add(this.projectMapMarker); // 添加点标记在地图上
          this.map.setZoom(13);
          this.map.setCenter(tip.location);
          this.regeoCode();
          break;
        }
      }
    },
    mapClick(e) {
      // 地图点击事件
      if (this.map !== undefined) {
        if (this.projectMapMarker !== undefined) {
          // 如果点标记已存在则先移除原点
          this.map.remove(this.projectMapMarker);
          this.lonLat = [];
        }
        this.projectMapMarker = new AMap.Marker({
          // 定义点标记对象
          position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat),
        });
        this.lonLat = [e.lnglat.lng, e.lnglat.lat];

        this.map.add(this.projectMapMarker); // 添加点标记在地图上
        this.regeoCode(); //把经纬度转化为地址
      }
    },
    // 设置地址
    regeoCode() {
      // 把拿到的经纬度转化为地址信息
      let geocoder = new AMap.Geocoder({
        city: "010", //城市设为北京，默认：“全国”
        radius: 1000, //范围，默认：500
      });
      const that = this; // 注意this指向问题
      let lnglat = this.lonLat;
      this.map.add(this.projectMapMarker);
      this.projectMapMarker.setPosition(lnglat);
      geocoder.getAddress(lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          // let street = result.regeocode.addressComponent.street;
          // let streetNumber = result.regeocode.addressComponent.streetNumber;
          // let township = result.regeocode.addressComponent.township;
          // console.log(street+streetNumber+township);

          // let sindex = result.regeocode.formattedAddress.indexOf('县');
          // that.address=result.regeocode.formattedAddress.substring(sindex+1)
          that.address = result.regeocode.formattedAddress;
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
  },
};
</script>

<style scoped>
.sear-map {
  margin-bottom: 20px;
}
</style>
